<template>
  <common-header/>
  <div class="center-container">
    <n-card class="center-card">
      <template #header>
        <div class="card-title">个人中心</div>
      </template>
      <n-form
          ref="formRef"
          :model="userForm"
          :rules="rules"
          label-placement="left"
          label-width="100"
          require-mark-placement="right-hanging"
          size="medium"
          class="custom-form"
      >
        <!-- 头像上传 -->
        <div class="avatar-container">
          <n-upload
              accept="image/*"
              :max="1"
              :default-file-list="avatarList"
              @change="handleAvatarChange"
              :custom-request="customRequest"
              @remove="handleAvatarRemove"
          >
            <n-avatar
                round
                :size="100"
                :src="userForm.avatarImgUrl ? BASE_URL + userForm.avatarImgUrl : '/default_avatar.svg'"
                class="upload-avatar"
            />
          </n-upload>
          <div class="upload-tip">点击更换头像</div>
        </div>

        <!-- 基本信息 -->
        <div class="form-content">
          <!-- 头像上传后增加选项卡 -->
          <n-tabs type="line" animated v-model:value="activeTab" class="info-tabs" @update:value="handleTabChange">
            <n-tab-pane name="basic" tab="基础信息">
              <n-grid :cols="1" :x-gap="12">
                <n-grid-item>
                  <n-form-item label="昵称" path="nickname">
                    <n-input v-model:value="userForm.nickname" placeholder="请输入昵称"/>
                  </n-form-item>
                </n-grid-item>
                <n-grid-item>
                  <n-form-item label="性别" path="gender">
                    <n-select
                        v-model:value="userForm.gender"
                        :options="genderOptions"
                        placeholder="请选择性别"
                        class="form-input"
                    />
                  </n-form-item>
                </n-grid-item>
                <n-grid-item>
                  <n-form-item label="电话" path="phone">
                    <n-input v-model:value="userForm.phone" placeholder="请输入电话号码" class="form-input"/>
                  </n-form-item>
                </n-grid-item>
                <n-grid-item>
                  <n-form-item label="生日" path="birth">
                    <n-date-picker
                        v-model:value="userForm.birth"
                        type="date"
                        class="form-input"
                        clearable
                        lang="zh-CN"
                        placeholder="请选择生日"
                    />
                  </n-form-item>
                </n-grid-item>
                <n-grid-item>
                  <n-form-item label="身高" path="height">
                    <n-input v-model:value="userForm.height" placeholder="请输入身高">
                      <template #suffix>cm</template>
                    </n-input>
                  </n-form-item>
                </n-grid-item>
                <n-grid-item>
                  <n-form-item label="体重" path="weight">
                    <n-input v-model:value="userForm.weight" placeholder="请输入体重">
                      <template #suffix>kg</template>
                    </n-input>
                  </n-form-item>
                </n-grid-item>
                <n-grid-item>
                  <n-form-item label="邮箱" path="email">
                    <n-input v-model:value="userForm.email" placeholder="请输入邮箱"/>
                  </n-form-item>
                </n-grid-item>
                <!-- 新增地址输入框 -->
                <n-grid-item>
                  <n-form-item label="地址" path="address" required>
                    <n-input v-model:value="userForm.address" placeholder="请输入地址"/>
                  </n-form-item>
                </n-grid-item>
              </n-grid>
            </n-tab-pane>

            <n-tab-pane v-if="isCoach" name="coach" tab="教练信息">
              <n-grid :cols="1" :x-gap="12">
                <!-- 修改资质证书为文件上传 -->
                <n-grid-item>
                  <n-form-item label="资质证书" path="certification">
                    <n-upload
                        v-if="!userForm.certification"
                        accept="image/*"
                        :max="1"
                        list-type="image-card"
                        :default-file-list="certificationList"
                        @change="handleCertChange"
                        :custom-request="handleCertUpload"
                        @remove="handleCertRemove"
                    >
                      点击或拖动图片到此处
                    </n-upload>
                    <n-space vertical v-else>
                      <n-image
                          :src="BASE_URL + userForm.certification"
                          width="200"
                          :preview-disabled="false"
                          object-fit="cover"
                      />
                      <n-button type="error" secondary @click="handleCertRemove({ url: userForm.certification })">
                        删除资质证书
                      </n-button>
                    </n-space>
                  </n-form-item>
                </n-grid-item>
                <n-grid-item>
                  <n-form-item label="擅长领域" path="specialty">
                    <n-input v-model:value="userForm.specialty" placeholder="请输入擅长领域"/>
                  </n-form-item>
                </n-grid-item>
                <n-grid-item>
                  <n-form-item label="课时费用" path="hourlyRate">
                    <n-input v-model:value="userForm.hourlyRate" placeholder="请输入课时费用">
                      <template #suffix>元/小时</template>
                    </n-input>
                  </n-form-item>
                </n-grid-item>
                <n-grid-item>
                  <n-form-item label="教学经验" path="teachingYears">
                    <!-- 修改教学年份输入框为整数输入 -->
                    <n-input-number
                        v-model:value="userForm.teachingYears"
                        placeholder="请输入教学经验"
                        :min="0"
                        :precision="0"
                    >
                      <template #suffix>年</template>
                    </n-input-number>
                  </n-form-item>
                </n-grid-item>
                <n-grid-item>
                  <n-form-item label="详细介绍" path="coachDesc">
                    <n-input
                        v-model:value="userForm.coachDesc"
                        type="textarea"
                        placeholder="请输入教练介绍"
                        :autosize="{ minRows: 3, maxRows: 5 }"
                    />
                  </n-form-item>
                </n-grid-item>
              </n-grid>
            </n-tab-pane>            <!-- 教练器械卡片管理选项卡 -->
            <n-tab-pane v-if="isCoach" name="coach-cards" tab="发布器械管理">
              <div class="coach-cards-management">
                <n-space vertical size="large">
                  <div class="cards-header">
                    <n-space justify="space-between" align="center">
                      <n-text strong size="large">我发布的器械卡片</n-text>
                      <n-button type="primary" @click="refreshCoachCards">
                        <template #icon>
                          <n-icon>
                            <RefreshOutline/>
                          </n-icon>
                        </template>
                        刷新
                      </n-button>
                    </n-space>
                  </div>

                  <n-spin :show="coachCardsLoading">
                    <div v-if="coachCards.length === 0" class="empty-cards">
                      <n-empty description="还没有发布任何器械卡片" size="large">
                        <template #extra>
                          <n-button size="small" @click="goToHomePage">去发布卡片</n-button>
                        </template>
                      </n-empty>
                    </div>

                    <n-grid v-else :cols="1" :y-gap="16">
                      <n-grid-item v-for="card in coachCards" :key="card.cardId">
                        <n-card class="card-item" hoverable>
                          <div class="card-content">
                            <div class="card-image">
                              <n-image
                                  :src="card.coverImg ? BASE_URL + card.coverImg : '/default_equipment.svg'"
                                  :fallback-src="'/default_equipment.svg'"
                                  width="120"
                                  height="80"
                                  object-fit="cover"
                              />
                            </div>
                            <div class="card-info">
                              <n-space vertical :size="8" style="flex: 1;">
                                <n-text strong>{{ card.title }}</n-text>
                                <n-text depth="3">部位：{{ card.bodyPart }}</n-text>
                                <n-text depth="3">发布时间：{{ formatDate(card.createTime) }}</n-text>
                              </n-space>
                            </div>
                            <div class="card-actions">
                              <n-space vertical>
                                <n-button
                                    type="error"
                                    size="small"
                                    @click="deleteCoachCard(card.cardId)"
                                >
                                  删除
                                </n-button>
                              </n-space>
                            </div>
                          </div>
                        </n-card>
                      </n-grid-item>
                    </n-grid>
                  </n-spin>
                </n-space>
              </div>
            </n-tab-pane>

            <!-- 教练课程管理选项卡 -->
            <n-tab-pane v-if="isCoach" name="coach-courses" tab="课程管理">
              <div class="coach-courses-management">
                <n-space vertical size="large">
                  <div class="courses-header">
                    <n-space justify="space-between" align="center">
                      <n-text strong size="large">我发布的课程</n-text>
                      <n-button type="primary" @click="refreshCoachCourses">
                        <template #icon>
                          <n-icon>
                            <RefreshOutline/>
                          </n-icon>
                        </template>
                        刷新
                      </n-button>
                    </n-space>
                  </div>

                  <n-spin :show="coachCoursesLoading">
                    <div v-if="coachCourses.length === 0" class="empty-courses">
                      <n-empty description="还没有发布任何课程" size="large">
                        <template #extra>
                          <n-button size="small" @click="goToCoursePage">去发布课程</n-button>
                        </template>
                      </n-empty>
                    </div>

                    <n-grid v-else :cols="1" :y-gap="16">
                      <n-grid-item v-for="course in coachCourses" :key="course.courseId">
                        <n-card class="course-item" hoverable>
                          <div class="course-content">
                            <div class="course-image">
                              <n-image
                                  :src="course.coverImg ? BASE_URL + course.coverImg : '/default_course.svg'"
                                  :fallback-src="'/default_course.svg'"
                                  width="120"
                                  height="80"
                                  object-fit="cover"
                              />
                            </div>
                            <div class="course-info">
                              <n-space vertical :size="8" style="flex: 1;">
                                <n-text strong>{{ course.title }}</n-text>
                                <n-text depth="3">发布时间：{{ formatDate(course.createTime) }}</n-text>
                              </n-space>
                            </div>
                            <div class="course-actions">
                              <n-space vertical>

                                <n-button
                                    type="error"
                                    size="small"
                                    @click="deleteCoachCourse(course.courseId)"
                                >
                                  删除
                                </n-button>
                              </n-space>
                            </div>
                          </div>
                        </n-card>
                      </n-grid-item>
                    </n-grid>
                  </n-spin>
                </n-space>
              </div>
            </n-tab-pane>

            <!-- 新增场馆人员管理选项卡 -->
            <n-tab-pane v-if="isGymStaff" name="gym-management" tab="场馆管理">
              <div class="gym-management-content">
                <n-space vertical size="large">
                  <n-alert type="info" title="场馆管理功能">
                    在这里您可以管理场馆信息、设置预约时段，并处理用户预约请求。
                  </n-alert>

                  <n-card title="快速操作" size="small">
                    <n-space>
                      <n-button type="primary" @click="goToGymManagement">
                        <template #icon>
                          <n-icon>
                            <BusinessOutline/>
                          </n-icon>
                        </template>
                        进入场馆管理
                      </n-button>
                      <n-button @click="viewReservations">
                        <template #icon>
                          <n-icon>
                            <CalendarOutline/>
                          </n-icon>
                        </template>
                        查看预约
                      </n-button>
                    </n-space>
                  </n-card>

                  <n-card title="操作说明" size="small">
                    <n-list>
                      <n-list-item>
                        <n-text>1. 首次使用需要创建场馆信息</n-text>
                      </n-list-item>
                      <n-list-item>
                        <n-text>2. 设置可预约的时间段和价格</n-text>
                      </n-list-item>
                      <n-list-item>
                        <n-text>3. 及时处理用户的预约请求</n-text>
                      </n-list-item>
                      <n-list-item>
                        <n-text>4. 定期更新场馆信息和设施</n-text>
                      </n-list-item>
                    </n-list>
                  </n-card>
                </n-space>
              </div>
            </n-tab-pane>

            <!-- 新增商家信息选项卡 -->
            <n-tab-pane v-if="isMerchant" name="merchant" tab="商家信息">
              <n-grid :cols="1" :x-gap="12">
                <!-- 营业执照上传 - 移到第一行 -->
                <n-grid-item>
                  <n-form-item label="营业执照" path="license">
                    <n-upload
                        v-if="!userForm.license"
                        accept="image/*"
                        :max="1"
                        list-type="image-card"
                        :default-file-list="licenseList"
                        @change="handleLicenseChange"
                        :custom-request="handleLicenseUpload"
                        @remove="handleLicenseRemove"
                    >
                      点击或拖动图片到此处
                    </n-upload>
                    <n-space vertical v-else>
                      <n-image
                          :src="BASE_URL + userForm.license"
                          width="200"
                          :preview-disabled="false"
                          object-fit="cover"
                      />
                      <n-button type="error" secondary @click="handleLicenseRemove({ url: userForm.license })">
                        删除营业执照
                      </n-button>
                    </n-space>
                  </n-form-item>
                </n-grid-item>
                <n-grid-item>
                  <n-form-item label="商家名称" path="merchantName">
                    <n-input v-model:value="userForm.merchantName" placeholder="请输入商家名称"/>
                  </n-form-item>
                </n-grid-item>

                <!-- 商家地址表单项，修改为与其他输入框等宽 -->
                <n-grid-item>
                  <n-form-item label="商家地址" path="address">
                    <div class="address-wrapper">
                      <n-input
                          v-model:value="userForm.address"
                          placeholder="请先在基础信息中填写地址"
                          readonly
                      />
                      <n-text depth="3" size="small" class="address-hint">
                        <n-icon size="14">
                          <InformationCircleOutline/>
                        </n-icon>
                        如需修改请在基础信息选项卡进行更改
                      </n-text>
                    </div>
                  </n-form-item>
                </n-grid-item>

                <n-grid-item>
                  <n-form-item label="商家描述" path="description">
                    <n-input
                        v-model:value="userForm.description"
                        type="textarea"
                        placeholder="请输入商家描述"
                        :autosize="{ minRows: 3, maxRows: 5 }"
                    />
                  </n-form-item>
                </n-grid-item>
              </n-grid>
            </n-tab-pane>            <!-- 购买订单管理选项卡 -->
            <n-tab-pane name="purchase-orders" tab="购买订单">
              <div class="orders-management">
                <n-space vertical size="large">
                  <div class="orders-header">
                    <n-space justify="space-between" align="center">
                      <n-text strong size="large">我的购买订单</n-text>
                      <n-button type="primary" @click="refreshPurchaseOrders">
                        <template #icon>
                          <n-icon>
                            <RefreshOutline/>
                          </n-icon>
                        </template>
                        刷新
                      </n-button>
                    </n-space>
                  </div>

                  <n-spin :show="purchaseOrdersLoading">
                    <div v-if="purchaseOrders.length === 0" class="empty-orders">
                      <n-empty description="还没有任何购买订单" size="large">
                        <template #extra>
                          <n-button size="small" @click="goToTradePage">去购买器械</n-button>
                        </template>
                      </n-empty>
                    </div>

                    <n-data-table
                        v-else
                        :columns="purchaseOrderColumns"
                        :data="purchaseOrders"
                        :row-key="row => row.orderId"
                        class="order-table"
                    />
                  </n-spin>
                </n-space>
              </div>
            </n-tab-pane>

            <!-- 销售订单管理选项卡 -->
            <n-tab-pane v-if="isMerchant" name="sales-orders" tab="销售订单">
              <div class="orders-management">
                <n-space vertical size="large">
                  <div class="orders-header">
                    <n-space justify="space-between" align="center">
                      <n-text strong size="large">我的销售订单</n-text>
                      <n-button type="primary" @click="refreshSalesOrders">
                        <template #icon>
                          <n-icon>
                            <RefreshOutline/>
                          </n-icon>
                        </template>
                        刷新
                      </n-button>
                    </n-space>
                  </div>

                  <n-spin :show="salesOrdersLoading">
                    <div v-if="salesOrders.length === 0" class="empty-orders">
                      <n-empty description="还没有任何销售订单" size="large">
                        <template #extra>
                          <n-button size="small" @click="goToTradePage">去上架器械</n-button>
                        </template>
                      </n-empty>
                    </div>

                    <n-data-table
                        v-else
                        :columns="salesOrderColumns"
                        :data="salesOrders"
                        :row-key="row => row.orderId"
                        class="order-table"
                    />
                  </n-spin>
                </n-space>
              </div>
            </n-tab-pane>

            <!-- 我的预约选项卡 -->
            <n-tab-pane name="my-reservations" tab="我的预约">
              <div class="reservations-management">
                <n-space vertical size="large">
                  <div class="reservations-header">
                    <n-space justify="space-between" align="center">
                      <n-text strong size="large">我的预约记录</n-text>
                      <n-button type="primary" @click="refreshReservations">
                        <template #icon>
                          <n-icon>
                            <RefreshOutline/>
                          </n-icon>
                        </template>
                        刷新
                      </n-button>
                    </n-space>
                  </div>

                  <n-spin :show="reservationsLoading">
                    <div v-if="myReservations.length === 0" class="empty-reservations">
                      <n-empty description="还没有任何预约记录" size="large">
                        <template #extra>
                          <n-button size="small" @click="goToGymPage">去预约场馆</n-button>
                        </template>
                      </n-empty>
                    </div>

                    <n-list v-else bordered>
                      <n-list-item v-for="reservation in myReservations" :key="reservation.id">
                        <n-card size="small" hoverable>
                          <div class="reservation-content">
                            <div class="reservation-info">
                              <n-space vertical size="small">
                                <n-text strong>{{ reservation.gymName }}</n-text>
                                <n-text depth="2">预约类型: {{ getReservationTypeName(reservation.reservationType) }}</n-text>
                                <n-text depth="2">预约日期: {{ formatDate(reservation.reservationDate) }}</n-text>
                                <n-text depth="2">时间段: {{ reservation.timeSlot }}</n-text>
                                <n-text depth="2" v-if="reservation.areaType">场地类型: {{ reservation.areaType }}</n-text>
                                <n-text depth="2" v-if="reservation.description">备注: {{ reservation.description }}</n-text>
                              </n-space>
                            </div>
                            <div class="reservation-actions">
                              <n-space vertical size="small">
                                <n-tag :type="getStatusTagType(reservation.status)">
                                  {{ getStatusText(reservation.status) }}
                                </n-tag>
                                <n-space size="small">
                                  <n-button 
                                    v-if="reservation.status === 1" 
                                    size="small" 
                                    type="error" 
                                    @click="cancelReservation(reservation.id)"
                                  >
                                    取消预约
                                  </n-button>
                                  <n-button 
                                    v-if="reservation.chatSessionId" 
                                    size="small" 
                                    type="primary" 
                                    @click="goToChat(reservation.chatSessionId)"
                                  >
                                    联系场馆
                                  </n-button>
                                </n-space>
                              </n-space>
                            </div>
                          </div>
                        </n-card>
                      </n-list-item>
                    </n-list>
                  </n-spin>
                </n-space>
              </div>
            </n-tab-pane>

            <!-- 我的上架器械选项卡 -->
            <n-tab-pane name="my-trades" tab="我的上架器械">
              <div class="trades-management">
                <n-space vertical size="large">
                  <div class="trades-header">
                    <n-space justify="space-between" align="center">
                      <n-text strong size="large">我上架的器械</n-text>
                      <n-button type="primary" @click="refreshMyTrades">
                        <template #icon>
                          <n-icon>
                            <RefreshOutline/>
                          </n-icon>
                        </template>
                        刷新
                      </n-button>
                    </n-space>
                  </div>

                  <n-spin :show="tradesLoading">
                    <div v-if="myTrades.length === 0" class="empty-trades">
                      <n-empty description="还没有上架任何器械" size="large">
                        <template #extra>
                          <n-button size="small" @click="goToTradePage">去上架器械</n-button>
                        </template>
                      </n-empty>
                    </div>

                    <n-grid v-else :cols="1" :y-gap="16">
                      <n-grid-item v-for="trade in myTrades" :key="trade.tradeId">
                        <n-card class="trade-card" hoverable>
                          <div class="trade-content">
                            <div class="trade-image">
                              <n-image
                                  :src="getTradeImageUrl(trade)"
                                  :fallback-src="'/default_equipment.svg'"
                                  width="120"
                                  height="120"
                                  object-fit="cover"
                                  :preview-disabled="false"
                                  @error="(e) => console.log('图片加载失败:', getTradeImageUrl(trade), e)"
                              />
                            </div>
                            <div class="trade-info">
                              <div class="trade-header">
                                <n-text strong size="large">{{ trade.equipmentName }}</n-text>
                                <n-tag
                                    :type="getTradeStatusType(trade.status)"
                                    size="small"
                                >
                                  {{ getTradeStatusText(trade.status) }}
                                </n-tag>
                              </div>
                              <n-space vertical size="small">
                                <n-text>价格: ¥{{ trade.price }}</n-text>
                                <n-text>数量: {{ trade.quantity }}</n-text>
                                <n-text depth="3" size="small">{{ trade.description }}</n-text>
                                <n-text depth="3" size="small">发布时间: {{ formatDate(trade.createTime) }}</n-text>
                              </n-space>
                            </div>
                            <div class="trade-actions">
                              <n-space vertical>
                                <n-button
                                    type="primary"
                                    size="small"
                                    @click="editTrade(trade)"
                                >
                                  编辑
                                </n-button>
                                <n-button
                                    type="error"
                                    size="small"
                                    @click="deleteTrade(trade.tradeId)"
                                >
                                  删除
                                </n-button>
                              </n-space>
                            </div>
                          </div>
                        </n-card>
                      </n-grid-item>
                    </n-grid>
                  </n-spin>
                </n-space>
              </div>
            </n-tab-pane>
          </n-tabs>
        </div>

        <!-- 提交按钮 - 场馆人员不显示保存按钮 -->
        <div v-if="!isGymStaff" class="form-content" style="display: flex; justify-content: center;">
          <n-form-item style="width: calc(100% - 60px); margin-left: 60px;">
            <n-button type="primary" size="medium" @click="handleSubmit" class="submit-button">
              保存修改
            </n-button>
          </n-form-item>
        </div>
      </n-form>
    </n-card>
  </div>

  <!-- 编辑交易模态框 -->
  <n-modal v-model:show="showEditModal" preset="dialog" title="编辑设备信息">
    <template #header>
      <div>编辑设备信息</div>
    </template>
    <n-form
        ref="editFormRef"
        :model="editTradeForm"
        :rules="editTradeRules"
        label-placement="left"
        label-width="100"
        require-mark-placement="right-hanging"
    >
      <n-form-item label="设备名称" path="equipmentName">
        <n-input v-model:value="editTradeForm.equipmentName" placeholder="请输入设备名称"/>
      </n-form-item>
      <n-form-item label="设备描述" path="equipmentDesc">
        <n-input
            v-model:value="editTradeForm.equipmentDesc"
            type="textarea"
            placeholder="请输入设备描述"
            :autosize="{ minRows: 3, maxRows: 5 }"
        />
      </n-form-item>
      <n-form-item label="价格" path="price">
        <n-input-number
            v-model:value="editTradeForm.price"
            placeholder="请输入价格"
            :min="0"
            :precision="2"
        >
          <template #suffix>元</template>
        </n-input-number>
      </n-form-item>
      <n-form-item label="数量" path="quantity">
        <n-input-number
            v-model:value="editTradeForm.quantity"
            placeholder="请输入数量"
            :min="1"
            :precision="0"
        />
      </n-form-item>
      <n-form-item label="设备图片" path="equipmentImgUrl">
        <n-upload
            v-if="!editTradeForm.equipmentImgUrl"
            accept="image/*"
            :max="1"
            list-type="image-card"
            @change="handleEditImageChange"
            :custom-request="handleEditImageUpload"
        >
          点击或拖动图片到此处
        </n-upload>
        <n-space vertical v-else>
          <n-image
              :src="getEditTradeImageUrl()"
              :fallback-src="'/default_equipment.svg'"
              width="200"
              :preview-disabled="false"
              object-fit="cover"
          />
          <n-button type="error" secondary @click="removeEditImage">
            删除图片
          </n-button>
        </n-space>
      </n-form-item>
    </n-form>
    <template #action>
      <n-space>
        <n-button @click="showEditModal = false">取消</n-button>
        <n-button type="primary" @click="saveTradeEdit">保存</n-button>
      </n-space>
    </template>
  </n-modal>
</template>

<script setup>
import {ref, onMounted, computed, h} from 'vue'
import {useMessage, createDiscreteApi} from 'naive-ui'
import axios from 'axios'
import CommonHeader from '../../components/CommonHeader.vue'
import qs from "qs";
import {useRouter} from 'vue-router'
import {Close, InformationCircleOutline, BusinessOutline, CalendarOutline, RefreshOutline} from '@vicons/ionicons5'  // 添加RefreshOutline图标
import http from '../../utils/http'

const message = useMessage()
const {dialog} = createDiscreteApi(['dialog'])
const formRef = ref(null)
const router = useRouter()

// 基础配置
const BASE_URL = 'http://localhost:8080'

// 获取全局getUser函数
const getUser = window.getUser

// 性别选项
const genderOptions = [
  {label: '男', value: 1},
  {label: '女', value: 2}
]

// 添加选项卡控制
const activeTab = ref('basic');

// 表单数据
const userForm = ref({
  // 基础信息
  userId: '',
  username: '',
  nickname: '',
  gender: null,
  phone: '',
  birth: null,
  height: null,
  weight: null,
  email: null,
  avatarImgUrl: null,
  role: null,
  address: '', // 新增地址字段

  // 教练信息
  certification: '',
  specialty: '',
  hourlyRate: null,
  teachingYears: null,
  coachDesc: '',
  // 商家信息
  merchantName: '',
  license: '',
  description: '',
})

// 预约管理相关数据
const myReservations = ref([])
const reservationsLoading = ref(false)

// 交易管理相关数据
const myTrades = ref([])
const tradesLoading = ref(false)
const showEditModal = ref(false)
const editFormRef = ref(null)
const editTradeForm = ref({
  tradeId: '',
  equipmentName: '',
  equipmentDesc: '',
  price: null,
  quantity: null,
  equipmentType: 'NEW', // 默认为新品器械
  conditionLevel: null, // 二手器械才需要
  equipmentImgUrl: '',
  images: [] // 添加images字段
})

// 教练管理相关数据
const coachCards = ref([])
const coachCardsLoading = ref(false)
const coachCourses = ref([])
const coachCoursesLoading = ref(false)

// 订单管理相关数据
const purchaseOrders = ref([])
const purchaseOrdersLoading = ref(false)
const salesOrders = ref([])
const salesOrdersLoading = ref(false)

// 编辑表单验证规则
const editTradeRules = {
  equipmentName: {
    required: true,
    message: '请输入设备名称',
    trigger: ['blur', 'input']
  },
  equipmentDesc: {
    required: true,
    message: '请输入设备描述',
    trigger: ['blur', 'input']
  },
  price: {
    required: true,
    type: 'number',
    message: '请输入价格',
    trigger: ['blur', 'change']
  },
  quantity: {
    required: true,
    type: 'number',
    message: '请输入数量',
    trigger: ['blur', 'change']
  }
}

// 表单验证规则
const rules = {
  phone: {
    validator: (rule, value) => {
      if (!value) return true; // 允许为空
      if (!/^1[3-9]\d{9}$/.test(value)) return new Error('请输入正确的手机号格式')
      return true
    },
    trigger: ['blur', 'input']
  },
  email: {
    type: 'email',
    required: false,
    message: '请输入正确的邮箱格式',
    trigger: ['blur', 'input']
  },

  // 身高验证
  height: {
    validator: (rule, value) => {
      if (!value) return true;
      const num = Number(value);
      if (isNaN(num)) return new Error('请输入有效的数字');
      if (num < 100 || num > 250) return new Error('请输入合理的身高(100-250cm)');
      return true;
    },
    trigger: ['blur', 'change', 'input']
  },
  // 体重验证
  weight: {
    validator: (rule, value) => {
      if (!value) return true;
      const num = Number(value);
      if (isNaN(num)) return new Error('请输入有效的数字');
      if (num < 30 || num > 200) return new Error('请输入合理的体重(30-200kg)');
      return true;
    },
    trigger: ['blur', 'change', 'input']
  },

  // 教练字段验证
  hourlyRate: {
    validator: (rule, value) => {
      if (!value) return true;
      const num = Number(value)
      if (isNaN(num)) return new Error('请输入有效的数字')
      if (num < 0) return new Error('课时费用不能为负数')
      return true
    },
    trigger: ['blur', 'input']
  },
  teachingYears: {
    validator: (rule, value) => {
      if (!value) return true;
      if (!Number.isInteger(value)) return new Error('请输入整数');
      if (value < 0) return new Error('教学经验不能为负数');
      return true;
    },
    trigger: ['blur', 'change', 'input']
  },
  address: {
    required: true,
    message: '请输入地址',
    trigger: ['blur', 'input']
  }
}

// 头像列表
const avatarList = ref([])

// 添加预览相关的响应式数据
const showPreview = ref(false)
const previewSrc = ref('')

// 修改证书列表的响应式数据结构为数组
const certificationList = ref([])

// 商家证件列表
const licenseList = ref([])

// 禁用未来日期
const disableFutureDate = (ts) => {
  return ts > Date.now();
};

// 日期格式化函数
const formatDate = (timestamp) => {
  if (!timestamp) return null;
  
  // 如果是字符串格式的日期（如 "2024-06-01"）
  if (typeof timestamp === 'string' && !timestamp.includes('T')) {
    return timestamp;
  }
  
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

// 订单状态文本映射
const getOrderStatusText = (status) => {
  const statusMap = {
    'PENDING': '待确认',
    'COMPLETED': '已完成',
    'DELIVERED': '已送达'
  }
  return statusMap[status] || status
}

// 订单状态标签类型
const getOrderStatusType = (status) => {
  const typeMap = {
    'PENDING': 'warning',
    'COMPLETED': 'success',
    'DELIVERED': 'info'
  }
  return typeMap[status] || 'default'
}

// 购买订单表格列定义
const purchaseOrderColumns = [
  {
    title: '订单号',
    key: 'orderId',
    width: 120
  },
  {
    title: '器械名称',
    key: 'equipmentName',
    width: 150
  },
  {
    title: '数量',
    key: 'quantity',
    width: 80,
    render(row) {
      return `${row.quantity}件`
    }
  },
  {
    title: '单价',
    key: 'price',
    width: 100,
    render(row) {
      return `¥${row.price.toFixed(2)}`
    }
  },
  {
    title: '总金额',
    key: 'totalAmount',
    width: 120,
    render(row) {
      return `¥${row.totalAmount.toFixed(2)}`
    }
  },
  {
    title: '状态',
    key: 'status',
    width: 100,
    render(row) {
      return h('n-tag', {
        type: getOrderStatusType(row.status),
        size: 'small'
      }, getOrderStatusText(row.status))
    }
  },
  {
    title: '下单时间',
    key: 'createTime',
    width: 180,
    render(row) {
      return new Date(row.createTime).toLocaleString()
    }
  },
  {
    title: '操作',
    key: 'actions',
    width: 100,
    render(row) {
      const actions = []

      if (row.status === 'COMPLETED') {
        actions.push(
            h('n-button', {
              size: 'small',
              type: 'primary',
              onClick: () => confirmReceipt(row.orderId)
            }, '确认收货')
        )
      }

      return h('n-space', {size: 'small'}, actions)
    }
  }
]

// 销售订单表格列定义
const salesOrderColumns = [
  {
    title: '订单号',
    key: 'orderId',
    width: 120
  },
  {
    title: '器械名称',
    key: 'equipmentName',
    width: 150
  },
  {
    title: '数量',
    key: 'quantity',
    width: 80,
    render(row) {
      return `${row.quantity}件`
    }
  },
  {
    title: '单价',
    key: 'price',
    width: 100,
    render(row) {
      return `¥${row.price.toFixed(2)}`
    }
  },
  {
    title: '总金额',
    key: 'totalAmount',
    width: 120,
    render(row) {
      return `¥${row.totalAmount.toFixed(2)}`
    }
  },
  {
    title: '状态',
    key: 'status',
    width: 100,
    render(row) {
      return h('n-tag', {
        type: getOrderStatusType(row.status),
        size: 'small'
      }, getOrderStatusText(row.status))
    }
  },
  {
    title: '下单时间',
    key: 'createTime',
    width: 180,
    render(row) {
      return new Date(row.createTime).toLocaleString()
    }
  },
  {
    title: '操作',
    key: 'actions',
    width: 100,
    render(row) {
      const actions = []

      if (row.status === 'PENDING') {
        actions.push(
            h('n-button', {
              size: 'small',
              type: 'primary',
              onClick: () => confirmOrder(row.orderId)
            }, '确认订单')
        )
      } else if (row.status === 'COMPLETED') {
        actions.push(
            h('n-button', {
              size: 'small',
              type: 'success',
              onClick: () => confirmDelivery(row.orderId)
            }, '确认送达')
        )
      }

      return h('n-space', {size: 'small'}, actions)
    }
  }
]

// 获取教练信息
const fetchCoachInfo = async (userId) => {
  try {
    const response = await axios.get(`${BASE_URL}/v1/coach/info/${userId}`);
    if (response.data.code === 2000) {
      const coachInfo = response.data.data;
      // 更新表单中的教练字段
      userForm.value.certification = coachInfo.certification;
      userForm.value.specialty = coachInfo.specialty;
      userForm.value.hourlyRate = coachInfo.hourlyRate;
      userForm.value.teachingYears = coachInfo.teachingYears;
      userForm.value.coachDesc = coachInfo.coachDesc;
    }
  } catch (error) {
    console.error('获取教练信息失败:', error);
  }
};

// 获取商家信息
const fetchMerchantInfo = async (userId) => {
  try {
    const response = await axios.get(`${BASE_URL}/v1/merchant/info/${userId}`);
    if (response.data.code === 2000) {
      const merchantInfo = response.data.data;
      // 更新表单中的商家字段
      userForm.value.merchantName = merchantInfo.name;
      userForm.value.address = merchantInfo.address;
      userForm.value.license = merchantInfo.license;
      userForm.value.description = merchantInfo.description;
    }
  } catch (error) {
    console.error('获取商家信息失败:', error);
  }
};

// 修改基础信息初始化函数
const initUserData = async () => {
  const user = getUser();
  if (user) {
    console.log('初始化用户数据:', user); // 调试日志

    // 重新从服务器获取最新的用户信息
    try {
      const response = await axios.get(BASE_URL + '/v1/user/selectByUserId', {
        params: {userId: user.userId}
      });

      if (response.data.code === 2000) {
        const latestUserData = response.data.data;
        console.log('从服务器获取的最新用户数据:', latestUserData);

        // 更新表单数据
        userForm.value = {
          // 基础信息
          userId: latestUserData.userId,
          username: latestUserData.username,
          nickname: latestUserData.nickname || '',
          gender: latestUserData.gender ? Number(latestUserData.gender) : null,
          phone: latestUserData.phone || '',
          birth: latestUserData.birth ? new Date(latestUserData.birth).getTime() : null,
          height: latestUserData.height || null,
          weight: latestUserData.weight || null,
          email: latestUserData.email || '',
          avatarImgUrl: latestUserData.avatarImgUrl || null,
          role: latestUserData.role,
          address: latestUserData.address || '',

          // 教练信息
          certification: latestUserData.coachInfo?.certification || '',
          specialty: latestUserData.coachInfo?.specialty || '',
          hourlyRate: latestUserData.coachInfo?.hourlyRate || null,
          teachingYears: latestUserData.coachInfo?.teachingYears || null,
          coachDesc: latestUserData.coachInfo?.coachDesc || '',

          // 商家信息
          merchantName: latestUserData.merchantInfo?.name || '',
          license: latestUserData.merchantInfo?.license || '',
          description: latestUserData.merchantInfo?.description || '',
        };

        console.log('更新后的表单数据:', userForm.value);

        // 更新本地存储
        const updatedUser = {
          ...latestUserData,
          tokenInfo: user.tokenInfo
        };
        localStorage.user = JSON.stringify(updatedUser);

        // 如果当前选项卡是预约，则加载预约数据
        if (activeTab.value === 'my-reservations') {
          await refreshReservations();
        }

      } else {
        console.error('获取用户信息失败:', response.data.msg);
        // 使用本地数据作为备用
        fallbackToLocalData(user);
      }
    } catch (error) {
      console.error('获取用户信息出错:', error);
      // 使用本地数据作为备用
      fallbackToLocalData(user);
    }
  }
};

// 备用数据初始化函数
const fallbackToLocalData = (user) => {
  userForm.value = {
    // 基础信息
    userId: user.userId,
    username: user.username,
    nickname: user.nickname || '',
    gender: user.gender ? Number(user.gender) : null,
    phone: user.phone || '',
    birth: user.birth ? new Date(user.birth).getTime() : null,
    height: user.height || null,
    weight: user.weight || null,
    email: user.email || '',
    avatarImgUrl: user.avatarImgUrl || null,
    role: user.role,
    address: user.address || '',

    // 教练信息
    certification: user.coachInfo?.certification || '',
    specialty: user.coachInfo?.specialty || '',
    hourlyRate: user.coachInfo?.hourlyRate || null,
    teachingYears: user.coachInfo?.teachingYears || null,
    coachDesc: user.coachInfo?.coachDesc || '',

    // 商家信息
    merchantName: user.merchantInfo?.name || '',
    license: user.merchantInfo?.license || '',
    description: user.merchantInfo?.description || '',
  };
};

// 头像上传处理函数
const handleAvatarChange = (options) => {
  const {file} = options;
  if (file.status === 'finished') {
    // 注意：这里需要正确处理返回的URL
    const fileUrl = file.url;
    // 更新头像预览
    avatarList.value = [{
      id: 'avatar',
      name: file.name,
      status: 'finished',
      url: fileUrl
    }];
  }
}

// 修改自定义上传请求函数
const customRequest = ({file}) => {
  const formData = new FormData();
  formData.append('file', file.file);

  axios.post(BASE_URL + '/v1/file/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then(response => {
    if (response.data.code === 2000) {
      const imageUrl = response.data.data;
      // 更新表单数据中的头像URL
      userForm.value.avatarImgUrl = imageUrl;

      // 直接更新用户信息，包含新的头像URL
      const submitData = {
        ...userForm.value,
        height: Number(userForm.value.height),
        weight: Number(userForm.value.weight),
        birth: userForm.value.birth ? formatDate(userForm.value.birth) : null,
        gender: Number(userForm.value.gender)
      };

      let data = qs.stringify(submitData);
      return axios.post(BASE_URL + '/v1/user/update', data);
    }
  }).then(response => {
    if (response && response.data.code === 2000) {
      // 更新本地存储
      const currentUser = JSON.parse(localStorage.user || '{}');
      const updatedUser = {
        ...response.data.data,
        tokenInfo: currentUser.tokenInfo
      };
      localStorage.user = JSON.stringify(updatedUser);
      message.success('头像更新成功');

      // 刷新页面显示
      initUserData();
    }
  }).catch(error => {
    console.error('头像上传失败:', error);
    message.error('头像上传失败，请稍后重试');
  });
}

// 处理头像删除
const handleAvatarRemove = (options) => {
  if (userForm.value.avatarImgUrl) {
    axios.post(BASE_URL + '/v1/file/remove', qs.stringify({
      imgUrl: userForm.value.avatarImgUrl
    })).then(response => {
      if (response.data.code === 2000) {
        // 清除用户头像
        const submitData = {
          ...userForm.value,
          avatarImgUrl: null
        };

        return axios.post(BASE_URL + '/v1/user/update', qs.stringify(submitData));
      }
    }).then(response => {
      if (response && response.data.code === 2000) {
        // 更新本地存储
        const currentUser = JSON.parse(localStorage.user || '{}');
        const updatedUser = {
          ...response.data.data,
          tokenInfo: currentUser.tokenInfo
        };
        localStorage.user = JSON.stringify(updatedUser);
        message.success('头像已删除');

        // 重新初始化数据
        initUserData();
      }
    }).catch(error => {
      console.error('头像删除失败:', error);
      message.error('头像删除失败，请稍后重试');
    });
  }
}

// 修改证书预览函数
const previewCert = (url) => {
  previewSrc.value = BASE_URL + url
  showPreview.value = true
}

// 证书上传处理函数
const handleCertChange = (options) => {
  const {file} = options;
  if (file.status === 'finished') {
    certificationList.value = [{
      id: 'cert',
      name: file.name,
      status: 'finished',
      url: file.url,
      thumbnailUrl: BASE_URL + file.url
    }];
  }
}

// 修改证书上传请求函数
const handleCertUpload = ({file}) => {
  const formData = new FormData();
  formData.append('file', file.file);

  axios.post(BASE_URL + '/v1/file/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then(response => {
    if (response.data.code === 2000) {
      const imageUrl = response.data.data;
      userForm.value.certification = imageUrl;
      message.success('证书上传成功');
    }
  }).catch(error => {
    console.error('证书上传失败:', error);
    message.error('证书上传失败，请稍后重试');
  });
}

// 证书删除处理函数
const handleCertRemove = (file) => {
  if (file.url) {
    axios.post(BASE_URL + '/v1/file/remove', qs.stringify({
      imgUrl: file.url
    })).then(response => {
      if (response.data.code === 2000) {
        certificationList.value = [];
        userForm.value.certification = null;
        message.success('证书已删除');
      }
    }).catch(error => {
      console.error('证书删除失败:', error);
      message.error('证书删除失败，请稍后重试');
    });
  }
}

// 商家证件上传处理
const handleLicenseChange = (options) => {
  const {file} = options;
  if (file.status === 'finished') {
    licenseList.value = [{
      id: 'license',
      name: file.name,
      status: 'finished',
      url: file.url,
      thumbnailUrl: BASE_URL + file.url
    }];
  }
}

const handleLicenseUpload = ({file}) => {
  const formData = new FormData();
  formData.append('file', file.file);

  return axios.post(BASE_URL + '/v1/file/upload', formData, {
    headers: {'Content-Type': 'multipart/form-data'}
  }).then(response => {
    if (response.data.code === 2000) {
      userForm.value.license = response.data.data;
      message.success('营业执照上传成功');
    }
  }).catch(error => {
    console.error('营业执照上传失败:', error);
    message.error('营业执照上传失败，请稍后重试');
  });
}

const handleLicenseRemove = (file) => {
  if (file.url) {
    axios.post(BASE_URL + '/v1/file/remove', qs.stringify({
      imgUrl: file.url
    })).then(response => {
      if (response.data.code === 2000) {
        licenseList.value = [];
        userForm.value.license = null;
        message.success('营业执照已删除');
      }
    }).catch(error => {
      console.error('营业执照删除失败:', error);
      message.error('营业执照删除失败，请稍后重试');
    });
  }
}

// 修改提交处理函数
const handleSubmit = () => {
  formRef.value?.validate(async (errors) => {
    if (!errors) {
      try {
        let response;
        console.log('提交数据，当前标签页:', activeTab.value);
        console.log('当前表单数据:', userForm.value);

        // 根据当前标签页提交对应数据
        if (activeTab.value === 'basic') {
          const basicData = {
            userId: userForm.value.userId,
            username: userForm.value.username,
            nickname: userForm.value.nickname,
            gender: userForm.value.gender,
            phone: userForm.value.phone,
            birth: userForm.value.birth ? formatDate(userForm.value.birth) : null,
            height: userForm.value.height,
            weight: userForm.value.weight,
            email: userForm.value.email,
            avatarImgUrl: userForm.value.avatarImgUrl,
            role: userForm.value.role,
            address: userForm.value.address
          };
          console.log('提交基础信息:', basicData);
          response = await axios.post(BASE_URL + '/v1/user/update', qs.stringify(basicData));
        } else if (activeTab.value === 'coach' && isCoach.value) {
          const coachData = {
            userId: userForm.value.userId,
            username: userForm.value.username,
            certification: userForm.value.certification,
            specialty: userForm.value.specialty,
            hourlyRate: userForm.value.hourlyRate,
            teachingYears: userForm.value.teachingYears,
            coachDesc: userForm.value.coachDesc
          };
          console.log('提交教练信息:', coachData);
          response = await axios.post(BASE_URL + '/v1/coach/update', qs.stringify(coachData));
        } else if (activeTab.value === 'merchant' && isMerchant.value) {
          const merchantData = {
            userId: userForm.value.userId,
            username: userForm.value.username,
            name: userForm.value.merchantName,
            license: userForm.value.license,
            description: userForm.value.description
          };
          console.log('提交商家信息:', merchantData);
          response = await axios.post(BASE_URL + '/v1/merchant/update', qs.stringify(merchantData));
        }

        if (response?.data?.code === 2000) {
          message.success('保存成功');
          // 重新初始化数据以获取最新信息
          await initUserData();

          // 触发用户信息更新事件
          window.dispatchEvent(new CustomEvent('user-updated'));
        } else {
          message.error(response?.data?.msg || '保存失败');
        }
      } catch (error) {
        console.error('提交失败:', error);
        message.error('保存失败，请稍后重试');
      }
    } else {
      console.log('表单验证失败:', errors);
      message.error('请检查表单填写是否正确');
    }
  });
};

// 性别和角色判断计算属性
const isCoach = computed(() => {
  const role = userForm.value.role;
  console.log('检查是否为教练，角色:', role);
  return role === 2;
});

const isMerchant = computed(() => {
  const role = userForm.value.role;
  console.log('检查是否为商家，角色:', role);
  return role === 3;
});

const isGymStaff = computed(() => {
  const role = userForm.value.role;
  console.log('检查是否为场馆人员，角色:', role);
  return role === 4;
});

// 场馆管理相关方法
const goToGymManagement = async () => {
  try {
    // 先检查用户是否已认领场馆
    const userInfo = getUser();
    if (userInfo) {
      const response = await axios.get(`${BASE_URL}/v1/gym/getByUserId`, {
        params: {userId: userInfo.userId}
      });

      if (response.data.code === 2000 && response.data.data) {
        // 已有场馆信息，直接跳转
        router.push('/gym/management');
      } else {
        // 没有场馆信息，提示去认领场馆
        message.info('您还没有认领场馆，请先到场馆详情页面认领场馆', {
          duration: 3000
        });
        // 跳转到场馆详情页
        router.push('/gym');
      }
    }
  } catch (error) {
    console.error('检查场馆信息失败:', error);
    message.warning('请先到场馆详情页面认领场馆');
    router.push('/gym');
  }
};

const viewReservations = () => {
  router.push('/gym/management?tab=reservations');
};

// 获取交易图片URL的辅助函数
const getTradeImageUrl = (trade) => {
  // 如果有images数组且不为空，返回第一张图片的完整URL
  if (trade.images && Array.isArray(trade.images) && trade.images.length > 0) {
    const imageUrl = trade.images[0];
    // 如果图片URL已经是完整URL，直接返回，否则拼接BASE_URL
    return imageUrl.startsWith('http') ? imageUrl : BASE_URL + imageUrl;
  }
  // 如果有equipmentImgUrl字段（兼容旧数据），使用它
  if (trade.equipmentImgUrl) {
    return trade.equipmentImgUrl.startsWith('http') ? trade.equipmentImgUrl : BASE_URL + trade.equipmentImgUrl;
  }
  // 都没有则返回默认图片
  return '/default_equipment.svg';
};

// 获取编辑表单图片URL的辅助函数
const getEditTradeImageUrl = () => {
  if (editTradeForm.value.equipmentImgUrl) {
    const imageUrl = editTradeForm.value.equipmentImgUrl;
    return imageUrl.startsWith('http') ? imageUrl : BASE_URL + imageUrl;
  }
  return '/default_equipment.svg';
};

// 预约管理相关方法
const refreshReservations = async () => {
  const user = getUser();
  if (!user) return;

  reservationsLoading.value = true;
  try {
    const response = await http.get('/v1/reservation/user', {
      params: { userId: user.userId }
    });
    if (response.data.code === 2000) {
      myReservations.value = response.data.data || [];
    } else {
      window.$message.error(response.data.message || '获取预约记录失败');
    }
  } catch (error) {
    console.error('获取预约记录失败:', error);
    window.$message.error('获取预约记录失败');
  } finally {
    reservationsLoading.value = false;
  }
};

// 获取预约类型名称
const getReservationTypeName = (type) => {
  const typeMap = {
    1: '场馆预约',
    2: '场地预约'
  };
  return typeMap[type] || '未知类型';
};

// 获取预约状态文本
const getStatusText = (status) => {
  const statusMap = {
    1: '待确认',
    2: '已确认',
    3: '已取消',
    4: '已完成'
  };
  return statusMap[status] || '未知状态';
};

// 获取状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    1: 'warning',
    2: 'success', 
    3: 'error',
    4: 'info'
  };
  return typeMap[status] || 'default';
};

// 取消预约
const cancelReservation = async (reservationId) => {
  try {
    const response = await http.post(`/v1/reservation/${reservationId}/cancel`);
    if (response.data.code === 2000) {
      window.$message.success('预约已取消');
      await refreshReservations();
    } else {
      window.$message.error(response.data.message || '取消预约失败');
    }
  } catch (error) {
    console.error('取消预约失败:', error);
    window.$message.error('取消预约失败');
  }
};

// 跳转到聊天界面
const goToChat = (chatSessionId) => {
  router.push(`/chat?sessionId=${chatSessionId}`);
};

// 跳转到场馆页面
const goToGymPage = () => {
  router.push('/gym');
};

// 交易管理相关方法
const refreshMyTrades = async () => {
  const user = getUser();
  if (!user) return;

  tradesLoading.value = true;
  try {
    const response = await axios.get(`${BASE_URL}/v1/trade/selectByUserId`, {
      params: {userId: user.userId}
    });
    if (response.data.code === 2000) {
      myTrades.value = response.data.data || [];
      console.log('获取的交易数据:', myTrades.value);
      // 检查图片路径
      myTrades.value.forEach((trade, index) => {
        console.log(`交易${index}:`, {
          tradeId: trade.tradeId,
          equipmentName: trade.equipmentName,
          images: trade.images,
          equipmentImgUrl: trade.equipmentImgUrl, // 兼容检查
          finalImageUrl: getTradeImageUrl(trade)
        });
      });
    } else {
      message.error('获取交易列表失败');
    }
  } catch (error) {
    console.error('获取交易列表失败:', error);
    message.error('获取交易列表失败');
  } finally {
    tradesLoading.value = false;
  }
};

const goToTradePage = () => {
  router.push('/trade');
};

const getTradeStatusType = (status) => {
  switch (status) {
    case 'AVAILABLE':
      return 'success';
    case 'UNAVAILABLE':
      return 'error';
    default:
      return 'default';
  }
};

const getTradeStatusText = (status) => {
  switch (status) {
    case 'AVAILABLE':
      return '可用';
    case 'UNAVAILABLE':
      return '已下架';
    default:
      return '未知';
  }
};

const editTrade = (trade) => {
  // 获取第一张图片作为编辑时的图片URL
  let imageUrl = null;
  if (trade.images && Array.isArray(trade.images) && trade.images.length > 0) {
    imageUrl = trade.images[0];
  } else if (trade.equipmentImgUrl) {
    imageUrl = trade.equipmentImgUrl;
  }
  editTradeForm.value = {
    tradeId: trade.tradeId,
    equipmentName: trade.equipmentName,
    equipmentDesc: trade.description, // 后端返回的是description字段
    price: trade.price,
    quantity: trade.quantity,
    equipmentType: trade.equipmentType || 'NEW', // 默认为新品器械
    conditionLevel: trade.conditionLevel || null, // 二手器械才需要
    equipmentImgUrl: imageUrl,
    images: trade.images || [] // 保存完整的images数组以备后用
  };
  showEditModal.value = true;
};

const deleteTrade = async (tradeId) => {
  const user = getUser();
  if (!user) {
    message.error('请先登录');
    return;
  }

  // 添加确认对话框
  dialog.warning({
    title: '确认删除',
    content: '确定要永久删除这件器械吗？删除后无法恢复。',
    positiveText: '确定删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        // 使用POST请求匹配后端接口
        const response = await axios.post(`${BASE_URL}/v1/trade/delete`, null, {
          params: {
            tradeId: tradeId,
            userId: user.userId
          }
        });
        if (response.data.code === 2000) {
          message.success('器械已永久删除');
          await refreshMyTrades();
        } else {
          message.error(response.data.msg || '删除失败');
        }
      } catch (error) {
        console.error('删除交易失败:', error);
        message.error('删除失败，请稍后重试');
      }
    }
  });
};

const saveTradeEdit = async () => {
  try {
    await editFormRef.value?.validate();

    // 转换字段名以匹配后端期望的数据结构
    const updateData = {
      tradeId: editTradeForm.value.tradeId,
      equipmentName: editTradeForm.value.equipmentName,
      description: editTradeForm.value.equipmentDesc, // 字段名转换
      price: editTradeForm.value.price,
      quantity: editTradeForm.value.quantity,
      equipmentType: editTradeForm.value.equipmentType, // 添加必填字段
      conditionLevel: editTradeForm.value.conditionLevel, // 添加条件字段
      images: editTradeForm.value.images || [],
      status: 'AVAILABLE' // 确保状态有效
    };

    console.log('发送更新数据:', updateData); // 调试日志

    const response = await axios.post(`${BASE_URL}/v1/trade/update`, updateData);
    if (response.data.code === 2000) {
      message.success('更新成功');
      showEditModal.value = false;
      await refreshMyTrades();
    } else {
      message.error('更新失败');
    }
  } catch (error) {
    console.error('更新交易失败:', error);
    if (error.message) {
      return; // 验证错误，不显示消息
    }
    message.error('更新失败');
  }
};

const handleEditImageChange = (options) => {
  // 图片变更处理
};

const handleEditImageUpload = async ({file, onFinish, onError}) => {
  const formData = new FormData();
  formData.append('file', file.file);

  try {
    const response = await axios.post(`${BASE_URL}/v1/upload/uploadImg`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });

    if (response.data.code === 2000) {
      editTradeForm.value.equipmentImgUrl = response.data.data;
      message.success('图片上传成功');
      onFinish();
    } else {
      message.error('图片上传失败');
      onError();
    }
  } catch (error) {
    console.error('图片上传失败:', error);
    message.error('图片上传失败');
    onError();
  }
};

const removeEditImage = () => {
  editTradeForm.value.equipmentImgUrl = '';
};

// 监听选项卡变化，当切换到"我的发布"时加载数据
const handleTabChange = (value) => {
  if (value === 'my-trades') {
    refreshMyTrades();
  } else if (value === 'coach-cards') {
    refreshCoachCards();
  } else if (value === 'coach-courses') {
    refreshCoachCourses();
  } else if (value === 'purchase-orders') {
    refreshPurchaseOrders();
  } else if (value === 'sales-orders') {
    refreshSalesOrders();
  } else if (value === 'my-reservations') {
    refreshReservations();
  }
};

// 订单管理相关方法
const refreshPurchaseOrders = async () => {
  purchaseOrdersLoading.value = true;
  try {
    const response = await axios.get(`${BASE_URL}/v1/order/my-purchases`, {
      headers: {
        'satoken': getUser()?.tokenInfo?.tokenValue
      }
    });

    if (response.data.code === 2000) {
      purchaseOrders.value = response.data.data || [];
      console.log('获取购买订单列表成功:', purchaseOrders.value);
    } else {
      message.error(response.data.msg || '获取购买订单失败');
    }
  } catch (error) {
    console.error('获取购买订单失败:', error);
    message.error('获取购买订单失败');
  } finally {
    purchaseOrdersLoading.value = false;
  }
};

const refreshSalesOrders = async () => {
  salesOrdersLoading.value = true;
  try {
    const response = await axios.get(`${BASE_URL}/v1/order/my-sales`, {
      headers: {
        'satoken': getUser()?.tokenInfo?.tokenValue
      }
    });

    if (response.data.code === 2000) {
      salesOrders.value = response.data.data || [];
      console.log('获取销售订单列表成功:', salesOrders.value);
    } else {
      message.error(response.data.msg || '获取销售订单失败');
    }
  } catch (error) {
    console.error('获取销售订单失败:', error);
    message.error('获取销售订单失败');
  } finally {
    salesOrdersLoading.value = false;
  }
};

// 买家确认收货
const confirmReceipt = async (orderId) => {
  try {
    const response = await axios.post(`${BASE_URL}/v1/order/update-status`, {
      orderId: orderId,
      status: 'DELIVERED'
    }, {
      headers: {
        'satoken': getUser()?.tokenInfo?.tokenValue,
        'Content-Type': 'application/json'
      }
    });

    if (response.data.code === 2000) {
      message.success('确认收货成功');
      await refreshPurchaseOrders();
    } else {
      message.error(response.data.msg || '确认收货失败');
    }
  } catch (error) {
    console.error('确认收货失败:', error);
    message.error('确认收货失败');
  }
};

// 卖家确认订单
const confirmOrder = async (orderId) => {
  try {
    const response = await axios.post(`${BASE_URL}/v1/order/update-status`, {
      orderId: orderId,
      status: 'COMPLETED'
    }, {
      headers: {
        'satoken': getUser()?.tokenInfo?.tokenValue,
        'Content-Type': 'application/json'
      }
    });

    if (response.data.code === 2000) {
      message.success('确认订单成功');
      await refreshSalesOrders();
    } else {
      message.error(response.data.msg || '确认订单失败');
    }
  } catch (error) {
    console.error('确认订单失败:', error);
    message.error('确认订单失败');
  }
};

// 卖家确认送达
const confirmDelivery = async (orderId) => {
  try {
    const response = await axios.post(`${BASE_URL}/v1/order/update-status`, {
      orderId: orderId,
      status: 'DELIVERED'
    }, {
      headers: {
        'satoken': getUser()?.tokenInfo?.tokenValue,
        'Content-Type': 'application/json'
      }
    });

    if (response.data.code === 2000) {
      message.success('确认送达成功');
      await refreshSalesOrders();
    } else {
      message.error(response.data.msg || '确认送达失败');
    }
  } catch (error) {
    console.error('确认送达失败:', error);
    message.error('确认送达失败');
  }
};

// 教练管理相关方法
const refreshCoachCards = async () => {
  const user = getUser();
  if (!user) return;

  coachCardsLoading.value = true;
  try {
    // 首先获取教练信息以获取coachId
    const coachResponse = await axios.get(`${BASE_URL}/v1/coach/selectByUserId`, {
      params: {userId: user.userId}
    });

    if (coachResponse.data.code === 2000 && coachResponse.data.data) {
      const coachId = coachResponse.data.data.coachId;
      
      // 获取所有器械卡片，然后筛选出当前教练发布的
      const response = await axios.get(`${BASE_URL}/v1/card/select`);

      if (response.data.code === 2000) {
        // 筛选出当前教练发布的器械卡片
        coachCards.value = response.data.data.filter(card =>
            card.coachId === coachId
        );
        console.log('获取教练器械卡片列表成功:', coachCards.value);
      } else {
        message.error(response.data.msg || '获取器械卡片列表失败');
      }
    } else {
      message.error('获取教练信息失败');
    }
  } catch (error) {
    console.error('获取教练器械卡片失败:', error);
    message.error('获取器械卡片列表失败');
  } finally {
    coachCardsLoading.value = false;
  }
};

const refreshCoachCourses = async () => {
  const user = getUser();
  if (!user) return;

  coachCoursesLoading.value = true;
  try {
    // 首先获取教练信息以获取coachId
    const coachResponse = await axios.get(`${BASE_URL}/v1/coach/selectByUserId`, {
      params: {userId: user.userId}
    });

    if (coachResponse.data.code === 2000 && coachResponse.data.data) {
      const coachId = coachResponse.data.data.coachId;

      // 获取教练发布的课程
      const coursesResponse = await axios.get(`${BASE_URL}/v1/course/select`);
      if (coursesResponse.data.code === 2000) {
        // 筛选出当前教练的课程
        coachCourses.value = coursesResponse.data.data.filter(course =>
            course.coachId === coachId
        );
        console.log('获取教练课程列表成功:', coachCourses.value);
      } else {
        message.error('获取课程列表失败');
      }
    } else {
      message.error('获取教练信息失败');
    }
  } catch (error) {
    console.error('获取教练课程失败:', error);
    message.error('获取课程列表失败');
  } finally {
    coachCoursesLoading.value = false;
  }
};

const editCoachCard = (card) => {
  // 初始化编辑表单数据
  editCardForm.value = {
    cardId: card.cardId,
    title: card.title,
    bodyPart: card.bodyPart,
    usageGuide: card.usageGuide,
    precautions: card.precautions,
    coverImg: card.coverImg
  };

  // 设置图片列表用于显示
  if (card.coverImg) {
    editCoverImgList.value = [{
      id: 'cover',
      name: 'cover.jpg',
      status: 'finished',
      url: BASE_URL + card.coverImg
    }];
  } else {
    editCoverImgList.value = [];
  }

  showEditCardModal.value = true;
};

const deleteCoachCard = async (cardId) => {
  try {
    // 使用URLSearchParams发送POST请求
    const params = new URLSearchParams();
    params.append('cardId', cardId);

    const response = await axios.post(`${BASE_URL}/v1/card/delete`, params, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    });

    if (response.data.code === 2000) {
      message.success('删除成功');
      await refreshCoachCards();
    } else {
      message.error(response.data.msg || '删除失败');
    }
  } catch (error) {
    console.error('删除器械卡片失败:', error);
    message.error('删除失败');
  }
};

const editCoachCourse = (course) => {
  // 跳转到课程页面并传递编辑参数
  router.push({
    path: '/course',
    query: {
      action: 'edit',
      courseId: course.courseId,
      type: 'course'
    }
  });
};

const deleteCoachCourse = async (courseId) => {
  const user = getUser();
  if (!user) return;

  try {
    // 首先获取教练信息以获取coachId
    const coachResponse = await axios.get(`${BASE_URL}/v1/coach/selectByUserId`, {
      params: {userId: user.userId}
    });

    if (coachResponse.data.code === 2000 && coachResponse.data.data) {
      const coachId = coachResponse.data.data.coachId;

      // 使用URLSearchParams正确发送表单数据
      const params = new URLSearchParams();
      params.append('courseId', courseId);
      params.append('coachId', coachId);

      const response = await axios.post(`${BASE_URL}/v1/course/delete`, params, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      });

      if (response.data.code === 2000) {
        message.success('删除成功');
        await refreshCoachCourses();
      } else {
        message.error(response.data.msg || '删除失败');
      }
    } else {
      message.error('获取教练信息失败');
    }
  } catch (error) {
    console.error('删除课程失败:', error);
    message.error('删除失败');
  }
};

const goToHomePage = () => {
  router.push('/');
};

const goToCoursePage = () => {
  router.push('/course');
};

// 组件挂载时初始化数据
onMounted(async () => {
  await initUserData();
})
</script>

<style scoped>
.center-container {
  max-width: 600px; /* 缩小整体宽度 */
  margin: 30px auto; /* 减小上下边距 */
  padding: 0 20px;
}

.center-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-title {
  font-size: 20px; /* 减小标题字号 */
  font-weight: bold;
  text-align: center;
  color: #333;
  padding: 8px 0;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30px;
}

.upload-avatar {
  cursor: pointer;
  transition: transform 0.3s;
}

.upload-avatar:hover {
  transform: scale(1.05);
}

.upload-tip {
  margin-top: 8px;
  color: #666;
  font-size: 14px;
}

.form-content {
  width: 100%;
  max-width: 480px; /* 增加最大宽度 */
  padding: 0 10px; /* 减小左右边距 */
}

.custom-form {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

:deep(.n-form-item-label) {
  width: 60px !important; /* 减小标签宽度 */
  flex: none !important;
}

:deep(.n-form-item-blank) {
  flex: 1;
  max-width: calc(100% - 70px); /* 增加输入框宽度 */
}

:deep(.n-input__input-el) {
  text-align: center;
}

:deep(.n-base-selection-label) {
  justify-content: center;
}

:deep(.n-form-item) {
  margin-bottom: 18px; /* 减小表单项间距 */
  display: flex;
  justify-content: center;
}

:deep(.n-input) {
  width: 100%;
}

:deep(.n-date-picker) {
  width: 100%;
}

:deep(.n-select) {
  width: 100%;
}

:deep(.n-form-item-label) {
  font-weight: 500;
  width: 80px !important; /* 固定标签宽度 */
  flex: none !important; /* 防止标签伸缩 */
}

:deep(.n-form-item-blank) {
  flex: 1; /* 让输入框占据剩余空间 */
}

:deep(.n-input-suffix) {
  color: #606266;
  font-size: 14px;
  padding-right: 8px;
}

.submit-button {
  width: 100%;
  margin-top: 12px;
}

:deep(.n-form-item:last-child) {
  margin-bottom: 0;
  margin-top: 24px;
  width: 100%;
}

/* 添加角色特有字段的样式 */
:deep(.n-divider) {
  margin: 24px 0;
}

:deep(.n-input-number) {
  width: 100%;
}

.info-tabs {
  margin-top: 20px;
  margin-bottom: 20px;
}

/* 商家地址提示样式 */
.address-wrapper {
  width: 100%;
  display: flex;
  flex-direction: column;
}

.address-hint {
  margin-top: 4px;
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #999;
}

/* 交易管理样式 */
.trades-management {
  width: 100%;
}

.trades-header {
  margin-bottom: 16px;
}

.empty-trades {
  text-align: center;
  padding: 40px 0;
}

.trade-card {
  border-radius: 8px;
  transition: all 0.3s ease;
}

.trade-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.trade-content {
  display: flex;
  gap: 16px;
  align-items: flex-start;
}

.trade-image {
  flex-shrink: 0;
}

.trade-info {
  flex: 1;
  min-width: 0;
}

.trade-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.trade-actions {
  flex-shrink: 0;
  margin-left: auto;
}

@media (max-width: 768px) {
  .trade-content {
    flex-direction: column;
  }

  .trade-actions {
    margin-left: 0;
    align-self: stretch;
  }
}

/* 订单管理样式 */
.orders-management {
  width: 100%;
}

.orders-header {
  margin-bottom: 16px;
}

.empty-orders {
  text-align: center;
  padding: 40px 0;
}

.order-table {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.n-data-table) {
  border-radius: 8px;
}

:deep(.n-data-table-th) {
  background-color: #f8f9fa;
  font-weight: 600;
}

:deep(.n-data-table-td) {
  padding: 12px 8px;
}

:deep(.n-data-table-tr:hover) {
  background-color: #f5f5f5;
}

@media (max-width: 768px) {
  .order-table {
    font-size: 12px;
  }

  :deep(.n-data-table-td) {
    padding: 8px 4px;
  }
}

/* 预约管理样式 */
.reservations-management {
  padding: 20px;
}

.reservations-header {
  margin-bottom: 20px;
}

.empty-reservations {
  text-align: center;
  padding: 40px 20px;
}

.reservation-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
}

.reservation-info {
  flex: 1;
}

.reservation-actions {
  flex-shrink: 0;
  text-align: right;
}

@media (max-width: 768px) {
  .reservation-content {
    flex-direction: column;
    gap: 10px;
  }
  
  .reservation-actions {
    text-align: left;
  }
}
</style>